package cn.com.surker.workcon.service.zhcl;

import cn.com.surker.base.strength.dao.BaseStrengthDao;
import cn.com.surker.base.strength.entity.BaseStrength;
import cn.com.surker.base.system.entity.SysLine;
import cn.com.surker.common.MessageCenterException;
import cn.com.surker.enums.production.invoice.InvoiceProcessEnum;
import cn.com.surker.enums.production.invoice.InvoiceSendTypeEnum;
import cn.com.surker.lab.dao.LabExpendUploadDao;
import cn.com.surker.lab.entity.LabExpendUpload;
import cn.com.surker.production.dao.ProductionIndentDao;
import cn.com.surker.production.entity.ProductionIndent;
import cn.com.surker.production.entity.ProductionIndentDispatch;
import cn.com.surker.production.entity.vo.ProductionIndentVo;
import cn.com.surker.util.DateUtil;
import cn.com.surker.util.MathUtils;
import cn.com.surker.util.StringUtils;
import cn.com.surker.workcon.common.GKJDBCService;
import cn.com.surker.workcon.service.ProduceService;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.jdbc.core.JdbcTemplate;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @author luotao
 * @date 2024/12/18
 */
@Slf4j
public class ProduceServiceImpl extends GKJDBCService implements ProduceService {


	@Resource
	private ProductionIndentDao indentDao;
	@Resource
	private LabExpendUploadDao labUploadDao;


	@Value("${erp.datasource.erp.db}")
	private String erpDb;

	@Override
	public int insert(Long lineId, ProductionIndentDispatch dispatch) {
		if (lineId == null || dispatch == null) {
			return -1;
		}
		SysLine line = getLine(lineId);
		JdbcTemplate lineTemplate = getLineJdbcTemp(line);
		//	没有数据源
		if (lineTemplate == null) {
			return -1;
		}
		//	任务单编号
		String indentCode = dispatch.getIndentCode();
		if (StringUtils.isBlank(indentCode)) {
			throw new MessageCenterException("派单" + dispatch.getCode() + "没有传入任务单编号数据");
		}
		Long indentId = dispatch.getIndentId();
		//	查询任务单数据
		ProductionIndentVo indentVo = indentDao.queryFullById(erpDb, indentId);
		if (indentVo == null) {
			throw new MessageCenterException("未查询出正确的任务单信息:(indentId)");
		}
		Integer uploadType = dispatch.getUploadType();
		if (InvoiceSendTypeEnum.SAND.getCode().equals(uploadType)) {
			indentCode = "R" + indentCode;
		}
		//	查询配合比数据
		List<LabExpendUpload> labExpendUploads = labUploadDao.queryByIndentId(erpDb, indentVo.getOrgId(), indentId, lineId);
		if (labExpendUploads == null || labExpendUploads.isEmpty()) {
			throw new MessageCenterException("派单未查询出配合比数据");
		}
		//	配合比编号
		String labLevelCode = null;
		for (LabExpendUpload expendUpload : labExpendUploads) {
			Long uploadLine = expendUpload.getUploadLine();
			if (lineId.equals(uploadLine)) {
				//	判断是否上传
				Integer isUpload = expendUpload.getIsUpload();
				if (isUpload != null && isUpload.equals(1)) {
					//	表示已经上传,获取配合比编号
					labLevelCode = expendUpload.getCode();
					break;
				}
			}
		}
		if (StringUtils.isBlank(labLevelCode)) {
			//	没有配合比编号
			throw new MessageCenterException("没有查询出上传的配合比编号,请重新上传配合比");
		}
		//	根据任务单编号,查询是否存在上传数据
		String productTaskTable = ZhclUtil.getCtrlTableName(line, "ProductTask");
		String queryOldTask = "select id from " + productTaskTable + " where Code = '" + indentCode + "'";
		//	查询数据
		List<Map<String, Object>> oldTasks = lineTemplate.queryForList(queryOldTask);
		if (oldTasks == null || oldTasks.isEmpty() || oldTasks.get(0) == null) {
			//	没有上传数据
			throw new MessageCenterException("任务单" + indentCode + "没有查询到工控数据,请重新上传配合比上传任务单");
		}
		//	查询该表的最大行号
		String distanceCtrlTable = ZhclUtil.getCtrlTableName(line, "DistanceCtrl");
		String queryMaxDuceSql = "select count(OrderID) from " + distanceCtrlTable;
		Long maxProduceId = lineTemplate.queryForObject(queryMaxDuceSql, Long.class);
		if (maxProduceId == null) {
			maxProduceId = 0l;
		}
		//	生产线id
		Long controlLineId = line.getControlLineId();
		//	站号和顺序号,规则为站号*10000+行序号
		long stationId = controlLineId * 10000 + 1;
		//	查询派单表最大的数据
		stationId += maxProduceId;
		//	派单序号
		Long dispatchId = dispatch.getId();
		//	合同名称
		String conName = indentVo.getConName();
		//	施工部位
		String site = indentVo.getSite();
		//	强度等级
		String strengthName = indentVo.getStrengthName();
		//	车号
		String carCode = dispatch.getCarCode();
		//	司机
		String driver = dispatch.getDriver();
		//	上传方量
		Double uploadStere = dispatch.getUploadStere();
		//	生产状态,默认为等到生产
		int productStatus = 0;
		//	派单类型
		int otherStatus = 1;
		if (InvoiceSendTypeEnum.SAND.getCode().equals(uploadType)) {
			// otherStatus = 0;
			labLevelCode = "R" + labLevelCode;
			// strengthName = "R" + strengthName;
			strengthName = "润管砂浆";
		}
		//	上传时间
		Date datTime = dispatch.getUploadTime();
		String tipText = DateUtil.convertString(datTime);
		String otherNum = DateUtil.convertString(datTime, "HHmmss");
		//	调度人员名
		String otherText = dispatch.getCreator();
		//	添加派单数据sql
		String insertSql = "insert into " + distanceCtrlTable + " (StationID,OrderID,PlanCode,PlanAlias,ProjectName,RecipeCode,RecipeName,ProductDosage,TruckCode,DriverName,ProductStatus,OtherStatus," +
			"ReProductDosage,ReRecipeCode,TipText,OtherNum,OtherText) " +
			" values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?) ";
		//	拼接参数
		Object[] pdParams = {stationId, dispatchId, indentCode, site, conName, labLevelCode, strengthName, uploadStere, carCode, driver, productStatus, otherStatus, null, null, tipText, otherNum, otherText};
		//	开启事务
		beginTransaction(lineId);
		//	插入数据
		int update = lineTemplate.update(insertSql, pdParams);
		return update;
	}

	public Integer queryByDispatchId(Long lineId, Long dispatchId) {
		if (lineId == null || dispatchId == null) {
			return null;
		}
		SysLine line = getLine(lineId);
		JdbcTemplate lineTemplate = getLineJdbcTemp(line);
		//	没有数据源
		if (lineTemplate == null) {
			return null;
		}
		String distanceCtrlTable = ZhclUtil.getCtrlTableName(line, "DistanceCtrl");
		//	查询工控机的生产状态
		String querySql = "select ProductStatus from " + distanceCtrlTable + " where OrderID = " + dispatchId;
		//	查询数据
		List<Map<String, Object>> maps = lineTemplate.queryForList(querySql);
		if (maps == null || maps.isEmpty()) {
			return null;
		}
		Map<String, Object> map = maps.get(0);
		if (map == null) {
			return null;
		}
		Object status = map.get("ProductStatus");
		if (status == null) {
			return null;
		}
		Integer tStatus = Integer.valueOf(String.valueOf(status));
		Integer prostats;
		if (tStatus == 0) {
			prostats = InvoiceProcessEnum.QUERN_PRO.getCode();
		} else if (tStatus > 3) {
			//	生产完成
			prostats = InvoiceProcessEnum.PRO_COMPLETE.getCode();
		} else {
			//	生产中
			prostats = InvoiceProcessEnum.PRO.getCode();
		}
		return prostats;
	}

	@Override
	public Boolean disHasDel(Long lineId, Long dispatchId) {
		if (lineId == null || dispatchId == null) {
			return null;
		}
		SysLine line = getLine(lineId);
		JdbcTemplate lineTemplate = getLineJdbcTemp(line);
		//	没有数据源
		if (lineTemplate == null) {
			return null;
		}
		String distanceCtrlTable = ZhclUtil.getCtrlTableName(line, "DistanceCtrl");
		//	查询工控机的生产状态,珠海长路的工控派单表没有表示是否被删除状态,根据表数据判定,如果没有数据,即表示被删除
		String querySql = "select ProductStatus from " + distanceCtrlTable + " where OrderID = " + dispatchId;
		//	查询数据
		List<Map<String, Object>> maps = lineTemplate.queryForList(querySql);
		boolean noData = false;
		if (maps == null || maps.isEmpty()) {
			noData = true;
		}
		Map<String, Object> map = maps.get(0);
		if (map == null) {
			noData = true;
		} else {
			Object productStatus = map.get("ProductStatus");
			if (productStatus != null) {
				Integer tStatus = Integer.valueOf(String.valueOf(productStatus));
				if (tStatus != null && tStatus.equals(6)) {
					//	6为待删除状态
					noData = true;
				}
			}
		}
		if (noData) {
			//	没有数据,查询是否有发货单
			String recordTableName = ZhclUtil.getRecordTableName(line, "N", "B");
			String queryRecordSql = "select BNo from " + recordTableName + " where OBNo = " + dispatchId;
			List<Map<String, Object>> maps1 = lineTemplate.queryForList(queryRecordSql);
			if (maps1 != null && maps1.size() > 0) {
				//	存在数据
				return false;
			} else {
				//	没有数据,确实删除了
				return true;
			}
		} else {
			return false;
		}
	}

	@Override
	public Integer delDispatch(Long lineId, Long dispatchId) {
		if (lineId == null || dispatchId == null) {
			return -1;
		}
		SysLine line = getLine(lineId);
		JdbcTemplate lineTemplate = getLineJdbcTemp(line);
		//	没有数据源
		if (lineTemplate == null) {
			return -1;
		}
		String distanceCtrlTable = ZhclUtil.getCtrlTableName(line, "DistanceCtrl");
		//	删除sql
		String delSql = "delete from " + distanceCtrlTable + " where OrderID = ? and ProductStatus = 0";
		Object[] params = {dispatchId};
		//	开启事务
		beginTransaction(lineId);
		int update = lineTemplate.update(delSql, params);
		return update;
	}
}


